<template>
  <view class="uni-container">
    <uni-forms ref="form" :value="formData" validateTrigger="bind">
      <uni-forms-item name="uid" label="发布者" required>
        <uni-data-checkbox :multiple="true" v-model="formData.uid" collection="lab-member" field="name as text, _id as value"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="label" label="标题" required>
        <uni-easyinput placeholder="标题" v-model="formData.label" trim="none"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="imageList" label="相关图片" required>
        <uni-file-picker file-mediatype="image" :limit="9" return-type="array" v-model="formData.imageList"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="desc" label="摘要" required>
        <uni-easyinput maxlength="-1" type="textarea" placeholder="摘要" v-model="formData.desc"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="date" label="发表时间" required>
        <uni-datetime-picker return-type="timestamp" v-model="formData.date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="open_url" label="成果获取网址">
        <uni-easyinput placeholder="点击跳转目标地址。如果是web地址则使用内置web-view打开；如果是本地页面则跳转本地页面；如果是schema地址则打开本地的app" v-model="formData.open_url" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="classifyId" label="类型" required>
        <uni-data-checkbox v-model="formData.classifyId" :localdata="formOptions.classifyId_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="status" label="是否发布" required>
        <switch @change="binddata('status', $event.detail.value)" :checked="formData.status"></switch>
      </uni-forms-item>
      <uni-forms-item name="content" label="主要内容">
        <!-- <uni-easyinput placeholder="主要内容" v-model="formData.content"></uni-easyinput> -->
		<Tinymce ref="editor" v-model="formData.content" :width="860" :height="400" />
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/lab-artitle.js';
  import Tinymce from '@/components/Tinymce'
  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'lab-artitle';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  export default {
	  components: {
	  	Tinymce,
	  },
    data() {
      let formData = {
        "uid": [],
        "label": "",
        "imageList": [],
        "desc": "",
        "date": null,
        "open_url": "",
        "classifyId": null,
        "status": false,
        "content": ""
      }
      return {
        formData,
        formOptions: {
          "classifyId_localdata": [
            {
              "value": 0,
              "text": "论文"
            },
            {
              "value": 1,
              "text": "会议"
            },
            {
              "value": 2,
              "text": "竞赛"
            },
            {
              "value": 3,
              "text": "专利"
            },
            {
              "value": 4,
              "text": "软著"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("uid,label,imageList,desc,date,open_url,classifyId,status,content").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
